import Board from "./Board";
import React from "react";
import { calculateWinner } from "./utils";
import "./index.css";

export default class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          // 九宫格中每个格子的状态，X|O|空
          squares: Array(9).fill(null),
        },
      ],
      // 标识下一个出现的符号
      xIsNext: true,
      // 当前进行的是哪一步
      stepNUmber: 0,
    };
  }
  handleClick = (i) => {
    const history = this.state.history.slice(0, this.state.stepNUmber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      // 如果又获胜者或者点击的地方已经填了X或者O，则什么都不做
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([{ squares }]),
      xIsNext: !this.state.xIsNext,
      stepNUmber: history.length,
    });
  };

  jumpTo(step) {
    this.setState({
      stepNUmber: step,
      xIsNext: step % 2 === 0,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNUmber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((item, index) => {
      const btnTitle = index ? `回到第${index}步` : `起始状态`;
      return (
        <li key={index}>
          <button
            onClick={() => {
              this.jumpTo(index);
            }}
          >
            {btnTitle}
          </button>
        </li>
      );
    });

    let status = "";
    if (winner) {
      status = `Winner: ${winner}`;
    } else {
      status = `Next player: ${this.state.xIsNext ? "X" : "O"}`;
    }
    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i) => {
              this.handleClick(i);
            }}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}
